package com.mccken.rapid.core.netty;

import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClientConfig;

import com.mccken.rapid.core.LifeCycle;
import com.mccken.rapid.core.RapidConfig;
import com.mccken.rapid.core.helper.AsyncHttpHelper;

import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.EventLoopGroup;
import lombok.extern.slf4j.Slf4j;

/**
 * HTTP 客户端启动类，主要用于下游服务的请求转发
 * 
 * @program: rapid_gateway
 * @description:
 * @author: mccken
 * @create: 2022-01-03 18:53
 **/
@Slf4j
public class NettyHttpClient implements LifeCycle {
	
	private AsyncHttpClient asyncHttpClient;
	
	private RapidConfig rapidConfig;
	
	private DefaultAsyncHttpClientConfig.Builder clientBuild;
	
	private EventLoopGroup eventLoopGroupWork;

	public NettyHttpClient(RapidConfig rapidConfig, EventLoopGroup eventLoopGroupWork) {
		this.rapidConfig = rapidConfig;
		this.eventLoopGroupWork = eventLoopGroupWork;
		// 初始化NettyHttpClient
		init();
	}

	@Override
	public void init() {
		this.clientBuild = new DefaultAsyncHttpClientConfig.Builder()
				.setFollowRedirect(false)
				.setEventLoopGroup(eventLoopGroupWork)
				.setConnectTimeout(rapidConfig.getHttpConnectTimeout())
				.setRequestTimeout(rapidConfig.getHttpRequestTimeout())
				.setMaxRequestRetry(rapidConfig.getHttpMaxRequestRetry())
				.setAllocator(PooledByteBufAllocator.DEFAULT)
				.setCompressionEnforced(true)
				.setMaxConnections(rapidConfig.getHttpMaxConnections())
				.setMaxConnectionsPerHost(rapidConfig.getHttpConnectionsPerHost())
				.setPooledConnectionIdleTimeout(rapidConfig.getHttpPooledConnectionIdleTimeout());
	}

	@Override
	public void start() {
		this.asyncHttpClient = new DefaultAsyncHttpClient(clientBuild.build());
		AsyncHttpHelper.getInstance().initialized(asyncHttpClient);
	}

	@Override
	public void shutdown() {
		if (asyncHttpClient != null) {
			try {
				asyncHttpClient.close();
			} catch (Exception e) {
				log.error("asyncHttpClient.close fail", e);
			}
		}
	}
}
